package com.sdkj.dspservice.modules.sys.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdkj.dspservice.common.base.entity.BaseResult;
import com.sdkj.dspservice.common.config.ProjectConfig;
import com.sdkj.dspservice.common.constant.HttpStatus;
import com.sdkj.dspservice.common.react.AntdProResult;
import com.sdkj.dspservice.common.utils.FileUtils;
import com.sdkj.dspservice.common.utils.Reflections;
import com.sdkj.dspservice.common.utils.StringUtils;
import com.sdkj.dspservice.modules.sys.entity.Annex;
import com.sdkj.dspservice.modules.sys.service.AnnexService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色表Controller
 *
 * @author tm
 */
@RestController
@RequestMapping(value = "${project-config.apiUrl}/${project-config.version}/sys/annex")
public class AnnexController {

    @Autowired
    private AnnexService annexService;
    @Autowired
    private ProjectConfig projectConfig;

    //    @RequiresPermissions("sys:annex:view")
    @RequestMapping(value = "get")
    public AntdProResult get(String id) {
        AntdProResult result = new AntdProResult();
        if (StringUtils.isNotBlank(id)) {
            Annex annex = annexService.getById(id);
            result.setData(annex);
        } else {
            result.error(HttpStatus.STATUS_400,
                    "id不能为空");
        }
        return result;
    }

    //    @RequiresPermissions("sys:annex:view")
    @RequestMapping(value = "list")
    public AntdProResult list(Annex annex) {
        AntdProResult result = new AntdProResult();
        List<Annex> list = annexService.list(new QueryWrapper<>());
        result.success(list);
        return result;
    }

    //    @RequiresPermissions("sys:annex:edit")
    @RequestMapping(value = "save", produces = MediaType.APPLICATION_JSON_VALUE)
    public BaseResult save(@Valid @RequestBody Annex annex) {
        BaseResult result = new BaseResult();
        annexService.saveOrUpdate(annex);
        return result;
    }

    //    @RequiresPermissions("sys:annex:edit")
    @RequestMapping(value = "remove")
    public BaseResult delete(String id, HttpServletResponse response) {
        BaseResult result = new BaseResult();
        if (StringUtils.isNotBlank(id)) {
            annexService.removeById(id);
        } else {
            response.setStatus(HttpStatus.STATUS_400);
            result.setErrorMessage("id不能为空");
        }
        return result;
    }

    /**
     * 获取数据源select列表
     *
     * @param annex
     * @return
     */
    @ApiOperation(value = "获取select列表")
    @GetMapping(value = "listForSelect")
    public AntdProResult listForSelect(Annex annex) {
        AntdProResult result = new AntdProResult();
        List<Annex> annexList = annexService.list(annex);
        // 转换为{label:xxx,value:xxx}
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Annex r : annexList) {
            Map<String, Object> map = new HashMap<>(2);
            map.put("label", r.getName());
            map.put("value", r.getId());
            mapList.add(map);
        }
        result.success(mapList);
        return result;
    }

    /**
     * 上传文件
     *
     * @param standardMultipartHttpServletRequest
     * @return
     */
    @RequestMapping(value = "upload")
    @ResponseBody
    public AntdProResult upload(StandardMultipartHttpServletRequest standardMultipartHttpServletRequest) {
        AntdProResult result = new AntdProResult();
        LinkedMultiValueMap<String, List<MultipartFile>> multipartFiles = (LinkedMultiValueMap<String, List<MultipartFile>>) Reflections.invokeGetter(standardMultipartHttpServletRequest, "multipartFiles");
        List<Annex> annexList = new ArrayList<>();
        for (String key : multipartFiles.keySet()) {
            MultipartFile multipartFile = (MultipartFile) multipartFiles.get(key).get(0);
            // 获取文件名
            String fileName = multipartFile.getOriginalFilename();
            // 写入文件
            String path = FileUtils.writeToFile(multipartFile, projectConfig.getUploadUrl() + File.separator + fileName, false);
            // 保存附件
            Annex annex = new Annex();
            annex.setUrl(path);
            annex.setName(fileName);
            annexService.saveOrUpdate(annex);
            annexList.add(annex);
        }
        if (multipartFiles.size() > 1) {
            result.success(annexList);
        } else {
            result.success(annexList.get(0));
        }
        return result;
    }

    /**
     * 下载文件
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "download")
    public void download(String id, HttpServletRequest request, HttpServletResponse response) {
        // 获取附件
        Annex annex = annexService.getById(id);
        // 下载文件
        FileUtils.downFile(new File(annex.getUrl()), request, response, annex.getName());
    }

    //    @RequiresPermissions("sys:annex:view")
    @RequestMapping(value = "listByIds")
    public AntdProResult listByIds(String ids) {
        AntdProResult result = new AntdProResult();
        List<Annex> list = annexService.listByIds(ids);
        result.success(list);
        return result;
    }

}